package rifl.meres4.commons;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.SwingWorker;

import rifl.meres4.commons.model.Software;
import rifl.meres4.commons.step.IWorkflowStep;
import rifl.meres4.commons.ui.StepFrame;

/**
 * Abstract Swing Worker class.
 * 
 * @author Mark Czotter
 * @author Miklos Szennai
 * 
 */
public class StepWorker extends
		SwingWorker<Software, Void> {
	
	protected Logger logger = Logger.getLogger(StepWorker.class.getCanonicalName());
	
	protected final StepFrame frame;
	
	protected Software software;

	private final IWorkflowStep step;

	public StepWorker(final StepFrame frame, final IWorkflowStep step) {
		this.frame = frame;
		this.step = step;
	}

	@Override
	protected Software doInBackground() throws Exception {
		try {
			if (!this.step.canDoStep()) {
				return null;
			}
			this.software = this.step.get();
			if (this.software != null) {
				this.step.doStep(this.software);
				this.step.put(this.software);
			}
			return this.software;
		} catch (Exception e) {
			logger.log(Level.SEVERE, "Exception when executing step: " + getClass().getName() + ": " + e.getMessage());
		}
		return null;
	}

	@Override
	protected void done() {
		String previousStepString = this.frame.getTextArea().getText();
		if (this.software != null) {
			this.frame.getTextArea().setText(previousStepString + "\n--------------\n" + this.software.toString() + "\n--------------\n");
		}
		if (!this.step.canDoStep()) {
			this.frame.getTextArea().setText(previousStepString + "\n--------------\nNext Service(s) currently unavailable! Try later!\n--------------\n");
		}
//		else {
//			this.frame.getTextArea().setText(previousStepString + "Software NULL!");
//		}
		if (this.step.hasInput() && this.frame != null) {
			this.frame.getNextButton().setEnabled(true);
		}
	}
	
	public StepFrame getFrame() {
		return this.frame;
	}
	
}
